﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.Model;

namespace StockFinder.Indicators.Day.ClosePrice
{
    public class YearPricePerformanceClosePriceIndicator : BaseDayIndicator
    {
        public YearPricePerformanceClosePriceIndicator(string indicatorName)
            : base(0, indicatorName)
        { }

        public YearPricePerformanceClosePriceIndicator(int lookbackPeriod, string indicatorName) 
            : base(lookbackPeriod, indicatorName)
        {}

        public override void ApplyIndicator(List<DailyPrice> prices)
        {
            if (!Initialize(prices)) return;

            var orderedPrices = prices.OrderByDescending(p => p.PriceDate);
            DailyPrice currentPrice;

            var pricesArray = orderedPrices.ToArray();       
            var pricesCount = orderedPrices.Count();

            //start from lookback period
            for (var i = 0; i < pricesCount; i++)
            {
                currentPrice = pricesArray[i];

                var takenPrices = pricesArray.Skip(i).ToArray();

                var c = (takenPrices.Length > 0) ? takenPrices[0].AdjustedClose : 0;
                var c1 = (takenPrices.Length > 62) ? takenPrices[62].AdjustedClose : takenPrices[takenPrices.Length - 1].AdjustedClose;
                var c2 = (takenPrices.Length > 125) ? takenPrices[125].AdjustedClose : takenPrices[takenPrices.Length - 1].AdjustedClose;
                var c3 = (takenPrices.Length > 188) ? takenPrices[188].AdjustedClose : takenPrices[takenPrices.Length - 1].AdjustedClose;
                var c4 = (takenPrices.Length > 251) ? takenPrices[251].AdjustedClose : takenPrices[takenPrices.Length - 1].AdjustedClose;

                var r1 = (c1 > 0) ? (((c - c1) / c1) * .4m) : 0;
                var r2 = (c2 > 0) ? (((c - c2) / c2) * .2m) : 0;
                var r3 = (c3 > 0) ? (((c - c3) / c3) * .2m) : 0;
                var r4 = (c4 > 0) ? (((c - c4) / c4) * .2m) : 0;

                var t1 = r1 + r2 + r3 + r4;

                var result = t1 * 100;

                currentPrice.DayIndicators[IndicatorName] = result;
            }
        }
    }
}
